package cn.com.agree.mybatisporelation.one2many.service.impl;

import cn.com.agree.mybatisporelation.one2many.controller.dto.AuthorDTO;
import cn.com.agree.mybatisporelation.one2many.controller.dto.BookDTO;
import cn.com.agree.mybatisporelation.one2many.dao.mapper.AuthorMapper;
import cn.com.agree.mybatisporelation.one2many.dao.mapper.BookMapper;
import cn.com.agree.mybatisporelation.one2many.dao.po.AuthorPO;
import cn.com.agree.mybatisporelation.one2many.dao.po.BookPO;
import cn.com.agree.mybatisporelation.one2many.service.BookService;
import cn.com.agree.mybatisporelation.one2many.service.exception.BizBookException;
import cn.hutool.core.bean.copier.BeanCopier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public BookDTO addBook(BookDTO bookDTO) {
        if (Objects.isNull(bookDTO.getAuthor()) || Objects.isNull(bookDTO.getAuthor().getId())) {
            throw new BizBookException("书籍所属作者不能为空");
        }
        AuthorPO authorPO = authorMapper.selectById(bookDTO.getAuthor().getId());
        if (Objects.isNull(authorPO)) {
            throw new BizBookException("书籍所属作者不存在");
        }
        BookPO bookPO = BeanCopier.create(bookDTO, new BookPO(), null).copy();
        bookPO.setAuthor(authorPO);
        bookMapper.insert(bookPO);

        return BeanCopier.create(bookPO, new BookDTO(), null).copy();
    }

    @Override
    public BookDTO getBook(Long id) {
        BookPO bookPO = bookMapper.findById(id);
        if (Objects.isNull(bookPO)) {
            throw new BizBookException("书籍不存在。");
        }
        return BeanCopier.create(bookPO, new BookDTO(), null).copy();
    }

    @Override
    public BookDTO getBookAnotherWay(Long id) {
        BookPO bookPO = bookMapper.findByIdAnotherWay(id);
        if (Objects.isNull(bookPO)) {
            throw new BizBookException("书籍不存在。");
        }
        return BeanCopier.create(bookPO, new BookDTO(), null).copy();
    }

}
